//
//  MBPhoneCodeViewController.m
//  Meboo
//
//  Created by kyo on 2023/11/21.
//

#import "MBPhoneCodeViewController.h"
#import <CRBoxInputView/CRBoxInputView.h>
#import <MSWeakTimer/MSWeakTimer.h>
#import "FirebaseAuth.h"
//#import "MBHomeViewController.h"
//#import "MBNickNameViewController.h"
//#import "MBTopicViewController.h"
#define DEFAULT_COUNT_DOWN_VALUE 60
@interface MBPhoneCodeViewController ()
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UILabel *codeLab;
@property (nonatomic, strong) UILabel *phoneLab;
@property (nonatomic, strong) UILabel *noticeLab;

@property (nonatomic, copy) NSString *codeStr;

@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, strong) CRBoxInputView *boxInputView;
@property (nonatomic, strong) CRBoxInputCellProperty *cellProperty;
@property (nonatomic, assign) NSInteger countDownValue;
@property (nonatomic, strong) MSWeakTimer *countDownTimer;
@property (nonatomic, strong) UIButton *resendBtn;
@property (nonatomic, strong) UIActivityIndicatorView *stateView;
@end

@implementation MBPhoneCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupUI];
    self.countDownValue = DEFAULT_COUNT_DOWN_VALUE;
    [self startCountDown];
}

#pragma mark - Public Method
- (void)setPhoneStr:(NSString *)phoneStr {
    _phoneStr = phoneStr;
    self.phoneLab.text = [NSString stringWithFormat:@"+1 %@",phoneStr];
}

#pragma mark - Private Method
- (void)startCountDown {
    self.resendBtn.enabled = NO;
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    self.countDownTimer = [MSWeakTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actionUpdateCountDownNumber) userInfo:nil repeats:YES dispatchQueue:mainQueue];
    [self.countDownTimer fire];
}

- (void)actionUpdateCountDownNumber {
    if (self.countDownValue > 0) {
//        [self.resendBtn setTitle:[NSString stringWithFormat:@"%lds Resend Code", self.countDownValue] forState:UIControlStateDisabled];
        // 创建一个NSMutableAttributedString，设置title和下划线样式
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%lds Resend Code", self.countDownValue]];
        [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSForegroundColorAttributeName value:HEXS(@"999999") range:NSMakeRange(0, attributedString.length)];
        // 将NSAttributedString设置为按钮的title
        [_resendBtn setAttributedTitle:attributedString forState:UIControlStateNormal];
    } else {
        [self.countDownTimer invalidate];
        self.countDownValue = DEFAULT_COUNT_DOWN_VALUE;
//        [self.resendBtn setTitle:@"Resend Code" forState:UIControlStateNormal];
        // 创建一个NSMutableAttributedString，设置title和下划线样式
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Resend Code"];
        [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSForegroundColorAttributeName value:HEXS(@"333333") range:NSMakeRange(0, attributedString.length)];
        // 将NSAttributedString设置为按钮的title
        [_resendBtn setAttributedTitle:attributedString forState:UIControlStateNormal];
        self.resendBtn.enabled = YES;
    }
    self.countDownValue -= 1;
}

#pragma mark - Action

- (void)leftAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)resendCode {
        __WeakSelf
    [self.stateView startAnimating];
    [[FIRPhoneAuthProvider provider] verifyPhoneNumber:[NSString stringWithFormat:@"+1%@",self.phoneStr]
                                            UIDelegate:nil
                                            completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
        [self.stateView stopAnimating];
      if (error) {
//        [self showMessagePrompt:error.localizedDescription];
          NSLog(@"%@",error.localizedDescription);
        return;
      }
      // Sign in using the verificationID and the code sent to the user
      // ...
        NSLog(@"%@",verificationID);
        weakSelf.verificationID = verificationID;
        [weakSelf startCountDown];
        
    }];
//    __WeakSelf
//    [[MBLoginDataManager sharedManager] getPhoneCodeWithPhone:[NSString stringWithFormat:@"1%@",self.phoneStr] success:^(BOOL success) {
//        [weakSelf startCountDown];
//    }];
}

- (void)nextAction {
    [self.stateView startAnimating];
    FIRAuthCredential *credential = [[FIRPhoneAuthProvider provider]
        credentialWithVerificationID:self.verificationID
                    verificationCode:self.codeStr];
    
    
    [[FIRAuth auth] signInWithCredential:credential
                              completion:^(FIRAuthDataResult * _Nullable authResult,
                                           NSError * _Nullable error) {

      if (error) {
        // ...
          NSLog(@"%@",error.localizedDescription);
        return;
      }
      // User successfully signed in. Get user data from the FIRUser object
      if (authResult == nil) { return; }
      FIRUser *user = authResult.user;
        
        [[MBLoginDataManager sharedManager] loginWithPhone:self.phoneStr code:self.codeStr userID:user.uid success:^(BOOL success) {
            AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if (success) {
                [MBProgressHUD showSuccessMessage:@"Login Success"];
                appDelegate.window.rootViewController = [[BaseTabBarViewController alloc]init];
            } else {
                [MBProgressHUD showErrorMessage:@"Login Fail"];
            }
            [self.stateView stopAnimating];
        }];
        
      // ...
    }];
    /**
     埋点 code
     登陆 101
     */
    [[NSIOApiManager sharedManager] setIOWithCode:@"101" content:@"phoneLogin"];
}

#pragma mark - UI
- (void)setupUI {
    
    [self.view addSubview:self.leftBtn];
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(15));
        make.top.mas_equalTo(StatusBarAndNavigationBarHeight-MBHeightScale(13)-MBHeightScale(20));
        make.height.width.mas_equalTo(MBHeightScale(20));
    }];
    
    [self.view addSubview:self.codeLab];
    [self.codeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.left.mas_equalTo(MBWidthScale(30));
        make.right.mas_equalTo(MBWidthScale(-30));
        make.top.mas_equalTo(MBHeightScale(10)+StatusBarAndNavigationBarHeight);
    }];
    
    [self.view addSubview:self.phoneLab];
    [self.phoneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeLab.mas_bottom).offset(MBHeightScale(22));
        make.right.mas_equalTo(MBWidthScale(-30));
        make.left.mas_equalTo(MBWidthScale(30));
    }];
    
    [self.view addSubview:self.boxInputView];
    [self.boxInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneLab.mas_bottom).offset(MBHeightScale(22));
        make.right.mas_equalTo(MBWidthScale(-30));
        make.left.mas_equalTo(MBWidthScale(30));
        make.height.mas_equalTo((ScreenWidth-MBWidthScale(60+25))/6);
    }];
    
    [self.view addSubview:self.noticeLab];
    [self.noticeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(30));
        make.right.mas_equalTo(MBWidthScale(-30));
        make.top.equalTo(self.boxInputView.mas_bottom).offset(10);
    }];
    
    [self.view addSubview:self.resendBtn];
    [self.resendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(MBWidthScale(22));
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.noticeLab.mas_bottom).offset(44);
    }];
    
    [self.view addSubview:self.nextBtn];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(30));
        make.right.mas_equalTo(MBWidthScale(-30));
        make.top.equalTo(self.resendBtn.mas_bottom).offset(21);
        make.height.mas_equalTo(MBHeightScale(56));
    }];
    
    [self.view addSubview:self.stateView];
    [self.stateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_top).offset(ScreenHeight/3);
    }];
}

#pragma mark - Setter && Getter

- (UIButton *)leftBtn {
    if (!_leftBtn) {
        _leftBtn = [[UIButton alloc] init];
        [_leftBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_leftBtn setImage:ImageWithName(@"login_back") forState:0];
        [_leftBtn addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBtn;
}

- (UILabel *)codeLab {
    if (!_codeLab) {
        _codeLab = [[UILabel alloc] init];
        _codeLab.font = MBHelBoldFontSizeScale(28);
        _codeLab.numberOfLines = 0;
        _codeLab.textColor = HEXS(@"333333");
        _codeLab.text = @"Verify your number";
    }
    return _codeLab;
}

- (UILabel *)phoneLab {
    if (!_phoneLab) {
        _phoneLab = [[UILabel alloc] init];
        _phoneLab.font = MBHelFontSizeScale(18);
        _phoneLab.textColor = HEXS(@"BBBBBB");
    }
    return _phoneLab;
}

- (UILabel *)noticeLab {
    if (!_noticeLab) {
        _noticeLab = [[UILabel alloc] init];
        _noticeLab.font = MBHelFontSizeScale(12);
        _noticeLab.numberOfLines = 0;
        _noticeLab.textColor = HEXS(@"333333");
        _noticeLab.text = @"Enter the 6-digit code you received.";
    }
    return _noticeLab;
}

- (UIButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [[UIButton alloc] init];
        [_nextBtn setTitle:@"Next" forState:0];
        _nextBtn.layer.cornerRadius = MBHeightScale(56/2);
        _nextBtn.titleLabel.font = MBHelFontSizeScale(16);
//        [_nextBtn setTitleColor:UIColor.whiteColor forState:0];
//        [_nextBtn setBackgroundColor:HEXS(@"22253C")];
        [_nextBtn setTitleColor:HEXS(@"BBBBBB") forState:0];
        [_nextBtn setBackgroundColor:HEXS(@"F5F7F9")];
        _nextBtn.enabled = NO;
        [_nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}

- (UIButton *)resendBtn {
    if (!_resendBtn) {
        _resendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_resendBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_resendBtn addTarget:self action:@selector(resendCode) forControlEvents:UIControlEventTouchUpInside];
//        [_resendBtn setTitle:@"60s Resend Code" forState:UIControlStateNormal];
        // 创建一个NSMutableAttributedString，设置title和下划线样式
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"60s Resend Code"];
        [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSForegroundColorAttributeName value:HEXS(@"999999") range:NSMakeRange(0, attributedString.length)];
        // 将NSAttributedString设置为按钮的title
        [_resendBtn setAttributedTitle:attributedString forState:UIControlStateNormal];
        _resendBtn.titleLabel.font = MBHelFontSizeScale(15);
        _resendBtn.enabled = NO;
    }
    return _resendBtn;
}

- (CRBoxInputView *)boxInputView {
    __WeakSelf
    if (!_boxInputView) {
        _boxInputView = [[CRBoxInputView alloc] initWithCodeLength:6];
        _boxInputView.keyBoardType = UIKeyboardTypeNumberPad;// 不设置时，默认UIKeyboardTypeNumberPad
        _boxInputView.textDidChangeblock = ^(NSString * _Nullable text, BOOL isFinished) {
            weakSelf.codeStr = text;
            if (isFinished) {
                [weakSelf.nextBtn setTitleColor:UIColor.whiteColor forState:0];
                [weakSelf.nextBtn setBackgroundColor:HEXS(@"22253C")];
                weakSelf.nextBtn.enabled = YES;
            } else {
                [weakSelf.nextBtn setTitleColor:HEXS(@"BBBBBB") forState:0];
                [weakSelf.nextBtn setBackgroundColor:HEXS(@"F5F7F9")];
                weakSelf.nextBtn.enabled = NO;
            }
        };
        // 输入类型（纯数字）
        _boxInputView.ifNeedCursor = NO;
        _boxInputView.inputType = CRInputType_Number;
        _boxInputView.boxFlowLayout.itemSize = CGSizeMake((ScreenWidth-MBWidthScale(60+25))/6, (ScreenWidth-MBWidthScale(60+25))/6);
        _boxInputView.boxFlowLayout.minLineSpacing = MBWidthScale(5);
        _boxInputView.customCellProperty = self.cellProperty;
        [_boxInputView loadAndPrepareViewWithBeginEdit:YES]; // BeginEdit:是否自动启用编辑模式
    }
    return _boxInputView;
}
- (CRBoxInputCellProperty *)cellProperty {
    if (!_cellProperty) {
        _cellProperty = [[CRBoxInputCellProperty alloc] init];
        _cellProperty.cellBorderColorNormal = HEXS(@"CDCDCD");
        _cellProperty.cellBorderColorSelected = HEXS(@"333333");
        _cellProperty.cellCursorWidth = 0;
        _cellProperty.cornerRadius = MBHeightScale(5);
        _cellProperty.borderWidth = 1;
        _cellProperty.cellFont = MBHelBoldFontSizeScale(20);
        _cellProperty.cellTextColor = HEXS(@"333333");
    }
    return _cellProperty;
}

- (UIActivityIndicatorView *)stateView {
    if (!_stateView) {
        _stateView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleLarge)];
    }
    return _stateView;
}
@end
